import 'dart:async';

typedef CountDownCallback = void Function(int leftSeconds, {int? days, int? hours, int? minutes, int? seconds});

class CountDown {
  late Timer _timer;
  late DateTime nowTime;
  late DateTime deadline;
  late CountDownCallback callback;

  CountDown(int timestamp, CountDownCallback callback) {
    if (timestamp.toString().length < 13) {
      /// 13 : 毫秒时间时的长度
      timestamp = timestamp * 1000;
    }
    deadline = DateTime.fromMillisecondsSinceEpoch(timestamp);
    this.callback = callback;
  }

  CountDown.fromNow(int seconds, CountDownCallback callback) {
    deadline = DateTime.now().add(Duration(seconds: seconds));
    this.callback = callback;
  }

  CountDown.dateTime(DateTime dateTime, CountDownCallback callback) {
    deadline = dateTime;
    this.callback = callback;
  }

  void startCountDown() {
    if (_timer?.isActive??false) {
      _timer.cancel();
    }

    nowTime = DateTime.now();
    const period = const Duration(seconds: 1);
    _timer = Timer.periodic(period, (timer) {
      nowTime = nowTime.add(period);
      int diff = deadline.difference(nowTime).inSeconds;
      if (diff < 1) {
        _timer.cancel();
        callback?.call(0);
        return;
      }

      /// 更新倒计时
      int days = deadline.difference(nowTime).inDays;
      int hours = deadline.difference(nowTime).inHours % 24;
      int minutes = deadline.difference(nowTime).inMinutes % 60;
      int seconds = diff % 60;
      callback?.call(diff, days: days, hours: hours, minutes: minutes, seconds: seconds);
    });
  }

  void dispose() {
    if (_timer?.isActive??false) {
      _timer?.cancel();
    }
  }
}